package com.zl.cms.controller;

import com.zl.basic.CommonUtil.JsonUtil;
import com.zl.cms.auth.AuthClass;
import com.zl.cms.auth.AuthMethod;
import com.zl.cms.dto.AjaxObj;
import com.zl.cms.dto.TopicDto;
import com.zl.cms.model.*;
import com.zl.cms.service.IAttachmentService;
import com.zl.cms.service.IChannelService;
import com.zl.cms.service.IKeywordService;
import com.zl.cms.service.ITopicService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-3-1 Time: 下午9:42
 */
@Controller
@AuthClass("login")
@RequestMapping("/admin/topic")
public class TopicController {

  private ITopicService topicService;
  private IChannelService channelService;
  private IKeywordService keywordService;
  private IAttachmentService attachmentService;

  public IAttachmentService getAttachmentService() {
    return attachmentService;
  }

  @Inject
  public void setAttachmentService(IAttachmentService attachmentService) {
    this.attachmentService = attachmentService;
  }

  private final static List<String> imgTypes = Arrays.asList("jpg", "png", "jpeg", "gif");

  public IKeywordService getKeywordService() {
    return keywordService;
  }

  @Inject
  public void setKeywordService(IKeywordService keywordService) {
    this.keywordService = keywordService;
  }

  public IChannelService getChannelService() {
    return channelService;
  }

  @Inject
  public void setChannelService(IChannelService channelService) {
    this.channelService = channelService;
  }

  public ITopicService getTopicService() {
    return topicService;
  }



  @Inject
  public void setTopicService(ITopicService topicService) {
    this.topicService = topicService;
  }

  private void initList(String con, Integer cid, Model model, HttpSession session, Integer status) {
    boolean isadmin = (Boolean) session.getAttribute("isAdmin");
    if (isadmin) {
      model.addAttribute("datas", topicService.find(cid, con, status));
    } else {
      User u = (User) session.getAttribute("loginUser");
      model.addAttribute("datas", topicService.find(u.getId(), cid, con, status));
    }
    if (null == con) con = "";
    model.addAttribute("con", con);
    model.addAttribute("cid", cid);
    model.addAttribute("cs", channelService.listPublishChannel());
  }

  @RequestMapping("/audits")
  @AuthMethod(role = "ROLE_PUBLISH,ROLE_AUDIT")
  public String auditList(@RequestParam(value = "con", required = false) String con,
      @RequestParam(value = "cid", required = false) Integer cid, Model model, HttpSession session) {
    initList(con, cid, model, session, 1);
    return "topic/audits";
  }

  @RequestMapping("/unaudits")
  @AuthMethod(role = "ROLE_PUBLISH,ROLE_AUDIT")
  public String unauditList(@RequestParam(value = "con", required = false) String con,
      @RequestParam(value = "cid", required = false) Integer cid, Model model, HttpSession session) {

    initList(con, cid, model, session, 0);
    return "topic/unaudits";
  }

  @RequestMapping(value = "/searchKeyword")
  @AuthMethod(role = "ROLE_PUBLISH")
  public @ResponseBody
  List<String> searchKeyword(String term) {
    System.out.println(keywordService.listKeywordstringByCon(term).toString());
    return keywordService.listKeywordstringByCon(term);
  }

  @RequestMapping("/changeStatus/{id}")
  @AuthMethod(role = "ROLE_AUDIT")
  public String changeStatus(@PathVariable int id, Integer status) {
    topicService.updateStatus(id);
    return status == 0 ? "redirect:/admin/topic/unaudits" : "redirect:/admin/topic/audits";
  }

  @RequestMapping("/delete/{id}")
  @AuthMethod(role = "ROLE_PUBLISH")
  public String delete(@PathVariable int id, Integer status) {
    topicService.delete(id);
    return status == 0 ? "redirect:/admin/topic/unaudits" : "redirect:/admin/topic/audits";
  }

  @RequestMapping(value = "/add", method = RequestMethod.GET)
  @AuthMethod(role = "ROLE_PUBLISH")
  public String add(Model model) {
    Topic t = new Topic();
    t.setPublishDate(new Date());
    TopicDto td = new TopicDto(t);
    model.addAttribute("topicDto", td);
    return "topic/add";
  }


	@RequestMapping(value="/add",method = RequestMethod.POST)
	public String add(@Validated TopicDto topicDto ,BindingResult br,String[] aks,Integer[] aids,HttpSession session) {
		if(br.hasErrors()) {
			return "topic/add";
		}
		Topic topic = topicDto.getTopic();
		User loginUser = (User)session.getAttribute("loginUser");
		StringBuilder sb = new StringBuilder();
		if(aks != null) {
			for(String key:aks) {
				sb.append(key).append("|");
				keywordService.addOrUpdate(key);
			}
		}
		topic.setKeyword(sb.toString());
		topicService.add(topic,Integer.parseInt(topicDto.getCid()),loginUser.getId(),aids);
		return "redirect:/admin/topic/unaudits";
	}


  @RequestMapping("/delete")
  @AuthMethod(role = "ROLE_PUBLISH")
  public void delete() {}


  @RequestMapping("/audit")
  @AuthMethod(role = "ROLE_AUDIT")
  public void audit() {}


  @RequestMapping("/treeAll")
  @AuthMethod(role = "ROLE_PUBLISH")
  public @ResponseBody
  List<ChannelTree> tree() {
    return channelService.generateTree();
  }


  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  // uploadif只能接收返回的值是字符串
  public void upload(MultipartFile attach, HttpServletResponse response) throws IOException {
    AjaxObj ao = null;
    try {
      response.setContentType("text/plain;charset=utf-8");
      Attachment att = new Attachment();
      String ext = FilenameUtils.getExtension(attach.getOriginalFilename());
      att.setAttch(0);
      if (imgTypes.contains(ext)) {
        att.setImg(1);
      } else {
        att.setImg(0);
      }
      att.setIndexPic(0);
      att.setNewName(System.currentTimeMillis() + "." + ext);
      att.setOldName(FilenameUtils.getBaseName(attach.getOriginalFilename()));
      att.setSuffix(ext);
      att.setType(attach.getContentType());
      att.setTopic(null);
      att.setSize(attach.getSize());
      attachmentService.add(att, attach.getInputStream());
      System.out.println(att.getId());
      ao = new AjaxObj(1, null, att);

    } catch (Exception e) {
      ao = new AjaxObj(0, e.getMessage());
    }

    response.getWriter().write(JsonUtil.getInstance().obj2Json(ao));
  }

  @RequestMapping(value = "/updateIndexPic", method = RequestMethod.POST)
  public void updateIndexPic(String aid) {
    attachmentService.updateIndexPic(Integer.parseInt(aid));
  }

  @RequestMapping(value = "/updateAttachInfo", method = RequestMethod.POST)
  public void updateAttachInfo(String aid) {
    attachmentService.updateAttachInfo(Integer.parseInt(aid));
  }

  @RequestMapping(value = "/deleteAtt", method = RequestMethod.POST)
  public void deleteAttach(String aid,HttpServletResponse response) {
	  try {
		  attachmentService.delete(Integer.parseInt(aid));
	  } catch (Exception e) {
		  try {
			  response.getWriter().write("{\"result\":0}");
		  } catch (IOException e1) {
			  e1.printStackTrace();
		  }
	  }
	  try {
		  response.getWriter().write("{\"result\":1}");
	  } catch (IOException e) {
		  e.printStackTrace();
	  }
  }
}
